package com.librarySys.librarySys.service;

import com.librarySys.librarySys.Bean.Authority;
import com.librarySys.librarySys.Bean.User;
import com.librarySys.librarySys.Mapper.CommonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailService<T extends User> implements UserDetailsService {

    @Autowired
    private CommonMapper commonMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        try {
            User user = commonMapper.getUserByUserName(s);
            System.out.println(user.getUsername());
            if (user == null){
                throw new UsernameNotFoundException("用户名不存在！");
            }
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            List<Authority> searchAuthorities = commonMapper.getAuthorityByUserId(user.getUserId());
            for (Authority authority:searchAuthorities){
                authorities.add(new SimpleGrantedAuthority(authority.getAuth()));
            }
            return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
